import 'dart:convert';
import 'dart:io';

import 'package:chatgpt_flutter/provider/theme_provider.dart';
import 'package:chatgpt_flutter/util/hi_const.dart';
import 'package:chatgpt_flutter/util/hi_dialog.dart';
import 'package:chatgpt_flutter/util/hi_utils.dart';
import 'package:chatgpt_flutter/widget/header_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:hi_download/hi_download.dart';
import 'package:login_sdk/dao/login_dao.dart';
import 'package:login_sdk/util/padding_extension.dart';
import 'package:provider/provider.dart';
import 'package:tyqw_flutter/http/ai_config.dart';
import 'package:wxyy_flutter/http/ai_config.dart';

import '../widget/theme_widget.dart';

// 我的页面
class MyPage extends StatefulWidget {
  const MyPage({Key? key}) : super(key: key);

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  String? avatar;
  String? userName;
  String? imoocId;
  static const titleStyle =
  TextStyle(fontSize: 18, fontWeight: FontWeight.w600);

  get _buildTitle => Container(
    // padding: const EdgeInsets.only(bottom: 10),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        const Padding(padding: EdgeInsets.only(left: 15, bottom: 10, right: 0)),
        // 15.paddingWidth,
        const Text('设置主题', style: titleStyle,),
        10.paddingWidth,
        Text('  请选择你喜欢的主题',
            style: TextStyle(fontSize: 13, color: Colors.grey[600]))
      ],
    ),
  );

  @override
  Widget build(BuildContext context) {
    var themeProvider = context.watch<ThemeProvider>();
    var color = themeProvider.themeColor;
    return Scaffold(
      body: Column(
        children: [
          HeaderWidget(
            avatar: avatar,
            name: userName,
            imoocId: imoocId,
          ),
          20.paddingHeight,
          const Divider(),
          ..._itemWidget(
              color: color,
              title: '检测更新',
              icon: Icons.update,
              onTap: _checkUpdate),
          ///因为是接入国内的模型，所以把有关代理的部分注释掉
          // ..._itemWidget(
          //     color: color,
          //     title: '设置代理',
          //     icon: Icons.network_check,
          //     onTap: _setProxy),
          ..._itemWidget(
            color: color,
            title: '选择模型',
            icon: Icons.network_check,
            onTap: _setModel,
          ),
          _buildTitle,
          ThemeWidget(onThemeChange: _onThemeChange)
        ],
      ),
    );
  }

  void _setModel() async {
    //获取默认的/之前设置过的模型
    var cacheModel = HiCache.getInstance().get(HiConst.selectModel);
    var result = await HiDialog.buildDropdown(context,
        selectModelText: cacheModel,
        onTap: () => HiUtils.openH5(
            'https://doc.devio.org/api-help/docs/ChatGPT-ProxySetting.html'));
    //点击取消
    if (!result[0]) {
      return;
    }
    String? selectModel = result[1];
    if (selectModel == 'qwen-turbo' || selectModel == 'qwen-plus' || selectModel == null || selectModel.isEmpty) {
      TYQW_AIConfigBuilder.init(HiConst.ali_apiKey);
      TYQW_AIConfigBuilder.instance.setModel(selectModel);
    } else if(selectModel  == 'ERNIE-Bot'){
      WXYY_AIConfigBuilder.init(chatUrl: HiConst.ERNIE_BOT_URL, apiKey: HiConst.Baidu_apiKey);
    }else{
      WXYY_AIConfigBuilder.init(chatUrl: HiConst.ERNIE_BOT_4_URL, apiKey: HiConst.Baidu_apiKey);
    }
    HiCache.getInstance().setString(HiConst.selectModel, selectModel!);
    var isSave = result[0];
    debugPrint('selectModel:$selectModel...isSave:$isSave');
  }

  @override
  void initState() {
    super.initState();
    Map<String, dynamic>? userInfo = LoginDao.getUserInfo();
    if (userInfo != null) {
      setState(() {
        userName = userInfo['userName'];
        imoocId = userInfo['imoocId'];
        avatar = userInfo['avatar'];
      });
    }
  }
  void _onThemeChange(String value) {
    context.read<ThemeProvider>().setTheme(colorName: value);
  }

  _itemWidget(
      {required Color color,
        required String title,
        required IconData icon,
        GestureTapCallback? onTap}) =>
      [
        10.paddingHeight,
        Container(
          alignment: Alignment.centerLeft,
          padding: const EdgeInsets.only(left: 15, bottom: 10, right: 20),
          child: InkWell(
            onTap: onTap,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  title,
                  style: titleStyle,
                ),
                Icon(icon, color: color)
              ],
            ),
          ),
        ),
        const Padding(
          padding: EdgeInsets.only(left: 15, right: 15),
          child: Divider(),
        )
      ];



  void _checkUpdate() {
  }

  // void _setProxy() async {
  //   //获取之前设置过的代理
  //   var cacheProxy = HiCache.getInstance().get(HiConst.keyHiProxy);
  //   var result = await HiDialog.showProxySettingDialog(context,
  //       proxyText: cacheProxy,
  //       onTap: () => HiUtils.openH5(
  //           'https://doc.devio.org/api-help/docs/ChatGPT-ProxySetting.html'));
  //   //点击取消
  //   if (!result[0]) {
  //     return;
  //   }
  //   String? proxy = result[1];
  //   AIConfigBuilder.instance.setProxy(proxy);
  //   if (proxy == null || proxy.isEmpty) {
  //     HiCache.getInstance().remove(HiConst.keyHiProxy);
  //   } else {
  //     HiCache.getInstance().setString(HiConst.keyHiProxy, proxy);
  //   }
  //   debugPrint('proxy:$proxy');
  // }
}
